package com.travel.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.travel.core.AbstractDao.Direction;
import com.travel.core.DaoFactory;
import com.travel.dao.ITourDao;
import com.travel.entities.Spot;

public class TopHotSpotsServlet extends HttpServlet {

    private static final long serialVersionUID = 966070974210305674L;

    private static final Logger LOGGER = LogManager.getLogger(TopHotSpotsServlet.class);

    private static final ITourDao TOUR_DAO = DaoFactory.getDao(ITourDao.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String type = request.getParameter("type");
        String orderBy;
        // 为何时间限制在2017年3月？？
        if ("0".equals(type)) {
            // 按评价数
            orderBy = "spotAvgRating";
        } else if ("1".equals(type)) {
            orderBy = "spotRatingCount";
        } else {
            orderBy = "spotAvgRating";
        }
        List<Spot> spots = TOUR_DAO.selectList("spotId", orderBy, Direction.DESC, 0, 10, true);
        JSONArray jsonArray = new JSONArray();
        for (Spot u : spots) {
            JSONObject json = new JSONObject();
            try {
                json.put("spotName", u.getSpotName());
                json.put("spotId", u.getSpotId());
                json.put("spotAvgRating", u.getSpotAvgRating());
                json.put("spotRatingCount", u.getSpotRatingCount());
            } catch (Exception e) {
                LOGGER.error(e.getLocalizedMessage(), e);
            }
            jsonArray.put(json);
        }

        response.setCharacterEncoding("utf-8");
        response.getWriter().append(jsonArray.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
